﻿<?php
session_start();
header ( 'Content-Type: text/html; charset=utf-8' );
ini_set ( 'date.timezone', 'Asia/Shanghai' );
//static $site_root="http://192.168.2.20";
static $log_access=TRUE;
//static $site_root="http://yao";
static $site_root="http://www.yaoyoa.com";
static $redirect_page="output.php";
static $archive_page="archive.php";
static $site_slogan="把握无限";
static $site_title="yaoyoa";
$site_right_str="<a href=\"http://www.miibeian.gov.cn\">鄂ICP备05006517号</a> ".sys_link("agreement");
$sys_topmenu="
	<div id=\"default_nav_ctn\">
		<div id=\"default_logo\"></div>
		<div id=\"dft_logo_text\"><a name=\"top\"> </a>$site_slogan</div>
		<div id=\"dft_nav_right_text\">".login_link(isset($login_state)?$login_state:"")."</div>
	</div>
	<div id=\"nav_menu_ctn\">
		<li>".sys_link("about")."</li>
		<li><a class=\"title_w\" href=\"\">企业服务</a></li>
		<li><a class=\"title_w\" href=\"tool.php\">工具箱</a></li>
		<li><a class=\"title_w\" href=\"content.php\">My Data</a></li>
	</div>
";
function sys_link($link_id){
	global $site_root;
	global $redirect_page;
	$link_class="";
	if ($link_id=="agreement"){
		$content_id=80;
		$link_name="访问许可和隐私条款";
	}
	if ($link_id=="about"){
		$content_id=80;
		$link_name="关于";
		$link_class="title_w";
	}
	$link_str="<a ".($link_class!=""?"class=\"$link_class\" ":"")."href=\"".$site_root."/".$redirect_page."?action=sys_info&content_id=$content_id\">$link_name</a>";
	return $link_str;
}
function login_link($login_state=""){
	if ($login_state==""){
		$login = new verify ();
		$login_state=$login->check_login("",FALSE);
	}
	$redirect_url=urlencode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
	
	if ($login_state===TRUE)
		return "欢迎您:".$_SESSION['yaoyoa_com_una']."<a href=\"javascript:logout_ajax();\">退出</a>"; 
	else 
		return "我Yao成为爻网会员|<a href=\"output.php?action=login&error_id=login_0009&redirect_url=$redirect_url\">登录</a>";
}
//**[replace_unclosed_tag]clear the content behind the unclosed tag
//echo replace_unclosed_tag("123M<45<>6你<>好<7>89");//result123M
function replace_unclosed_tag($input_string){
	$pos=0;
	for($k = 1; $k <= mb_strlen ( $input_string, 'UTF-8' ); $k ++) {
		$a=mb_substr ( $input_string, 0-$k, 1, 'UTF-8' );
		if ($a=="<"){
			$pos=$k;
			break;
		}
		elseif ($a==">"){
			$pos=0;
			break;
		}
	}
	return mb_substr($input_string,0,mb_strlen ($input_string, 'UTF-8' )-$pos,'UTF-8');
}

function db_connect($db_ip="localhost",$db_uid="s420448db0",$db_pwd="36mt7jg6",$db_name="s420448db0"){
//function db_connect($db_ip = "localhost", $db_uid = "root", $db_pwd = "123", $db_name = "yaoyoa") {
//function db_connect($db_ip = "localhost", $db_uid = "root", $db_pwd = "!@#$", $db_name = "yaoyoa") {
	@$result = new mysqli ( $db_ip, $db_uid, $db_pwd, $db_name );
	$error_handle=new error_handle();
	if (mysqli_connect_errno ()||! $result) {
		$error_handle->call_error("sys_0001");
	}
	else {
		mysqli_query ( $result, "set names 'utf8'" );
		return $result;
	}
}
function db_result_to_array($result) {
	$des_array = array ();
	While ($des_row = $result->fetch_assoc () )
		$des_array[]=$des_row;
//	if ($result && $result->num_rows > 0)
//		for($count = 0; $row = $result->fetch_assoc (); $count ++) //fetch_row  fetch_assoc fetch_array
//			$des_array [] = $row;
	return $des_array;
}
//$ss = new error_handle ( );
//$ss->error_report("login","www.ddd","yao");
class error_handle{
	function call_error($error_id="",$target_url="",$parameter=TRUE){
		global $redirect_page;
		if ($parameter)
			$redirect_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		else
			$redirect_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
		if ($target_url!="")$redirect_url=$target_url;
		if (strpos($redirect_url,$redirect_page))
			$redirect_url="default.php";
		$redirect_url=urlencode(($redirect_url));
		global $site_root;
		header( "Location: $site_root/$redirect_page?error_id=".$error_id."&redirect_url=".$redirect_url );
		die();
	}
	function get_error_info($error_id=""){
		if ($error_id=="")return FALSE;
		$conn = @db_connect ();
		$sql_str = "select title,content,error_type from error_definition where error_id='$error_id'";
		$result = $conn->query ( $sql_str );
		if (! $result || $result->num_rows == 0)
			return FALSE;
		else
			return db_result_to_array($result);
	}
	function error_report($error_type="",$error_link,$relate_uid,$ip_analyse=FALSE){
		$data_manage=new data_manage();
		$log_access=new log();
		if($ip_analyse){
			$access_id=$log_access->track(TRUE);
		}else
			$access_id=$log_access->track();
		$data_array=array("error_type"=>$error_type,"error_link"=>$error_link,"relate_uid"=>$relate_uid,"update_time"=>date("Y-m-d H:i:s"),"access_id"=>$access_id);
		$data_manage->update_array($data_array,"error_report",$update_type="insert");
	}
}
class verify {
	function logout(){
		if (isset($_SESSION['yaoyoa_com_uid']))unset($_SESSION['yaoyoa_com_uid']);
		if (isset($_SESSION['yaoyoa_com_uid']))unset($_SESSION['yaoyoa_com_uid']);
	}
	function check_login($check_right=FALSE,$force_login=TRUE,$uid="",$pwd="",$target_url="",$pwd_state="encrypt",$login_event=FALSE){
		if ($force_login)$error_handle=new error_handle();
		if ($uid==""){
			if (isset($_SESSION['yaoyoa_com_uid'])){
				if ($_SESSION['yaoyoa_com_uid']!=""){
					$uid=$_SESSION['yaoyoa_com_uid'];
				}
				else
					if ($force_login){
						$error_handle->call_error("login_0008",$target_url);
					}else{
						return FALSE;
					}
			}
			else{
				if ($force_login){
					$error_handle->call_error("login_0008",$target_url);
				}else{
					return FALSE;
				}
			}
		}
		if ($pwd==""){
			if (isset($_SESSION['yaoyoa_com_pwd'])){
				if ($_SESSION['yaoyoa_com_pwd']!="")
					$pwd=$_SESSION['yaoyoa_com_pwd'];
				else
					if ($force_login){
						$error_handle->call_error("login_0008",$target_url);
					}else{
						return FALSE;
					}
			}
			else
				if ($force_login){
					$error_handle->call_error("login_0008",$target_url);
				}else{
					return FALSE;
				}
		}
		$conn = @db_connect ();
		$sql_str = "select pwd,user_name from member where uid='$uid' and (member_state<>0 or isnull(member_state))";
		$result = $conn->query ( $sql_str );
		if (! $result || $result->num_rows == 0)
			if ($force_login){
				$error_handle->call_error("login_0008",$target_url);
			}else{
				return FALSE;
			}
		else
			$result=db_result_to_array($result);
		if ($pwd_state=="original")$pwd=md5($pwd);
		if ($pwd==md5($result[0]['pwd'])){
			if ($login_event){
				$_SESSION['yaoyoa_com_uid']=$uid;
				$_SESSION['yaoyoa_com_pwd']=$pwd;
				$_SESSION['yaoyoa_com_una']=$result[0]['user_name'];
			}
			if ($check_right!==FALSE&&$check_right!=""){
				if ($this->analyse_right($uid,$check_right)===FALSE)
					if ($force_login){
						$error_handle->call_error("login_0006",$target_url);
					}else{
						return FALSE;
					}
			}
			return TRUE;
		}
		else{
//			$track=new log();
//			$track->track();
			if ($force_login){
				$error_handle->call_error("login_0005",$target_url);
			}else{
				return FALSE;
			}
		}
	}
	function get_right($check_id = "",$check_right="", $check_type = "user_id") {
		if ($check_id == "")
			return "error_001";
		$conn = @db_connect ();
		$sql_str = "select check_id,control_list,id_type,audit_type from access_control_list";
		if ($check_type == "user_id") {
			$sql_str .= " where (check_id='all' or control_list='all' or check_id='$check_id'";
			$group_id = $this->get_group ( $check_id );
			if ($group_id [0] ['group_id'] != "")
				$sql_str .= " or check_id='" . $group_id [0] ['group_id'] . "'";
		}
		if ($check_type == "group_id")
			$sql_str .= " where (check_id='$check_id' or check_id='all' or control_list='all'";
		if ($check_right!=""){
			$sql_str.=") and ((";
			if (is_array($check_right)){
				foreach ($check_right as $right_val)
					$sql_str.=" control_list like '%$right_val%' or";
				$sql_str=substr($sql_str,0,strlen($sql_str)-2);
			}
			else
				$sql_str.="control_list like '%$check_right%'";
			$sql_str.=") or control_list='all')";
		}else {
			$sql_str.=")";
		}
		$result = $conn->query ( $sql_str );
		if (! $result || $result->num_rows == 0)
			return FALSE;
		else
			return ($result);
	}
	function get_group($user_id = "") {
		if ($user_id == "")
			return FALSE;
		$conn = @db_connect ();
		$sql_str = "select group_id from member where uid='$user_id'";
		$result = $conn->query ( $sql_str );
		if (! $result || $result->num_rows == 0)
			return "err_000";
		else
			return db_result_to_array ( $result );
	}
	function analyse_right($user_id = "", $check_right = "") {
		if ($user_id == "")
			return FALSE;
		$right_array = $this->get_right ( $user_id,$check_right );
		if ($right_array===FALSE)return FALSE;
		$right_array_sort = $this->format_right ( $right_array );
		$right_result = FALSE;
//		print_r($right_array_sort);
		foreach ( $right_array_sort ['user_id'] as $val ) {
			if ($val['check_id']=='all'){
				if ($val ['audit_type'] == 1)
					$right_array_temp['user_id']['all']['allow']=TRUE;
				elseif ($val['audit_type'] == 0)
					$right_array_temp['user_id']['all']['deny']=TRUE;
			}
			if ($val['check_id']==$user_id){
				if($val['audit_type'] == 0)
					$right_array_temp['user_id']['self']['deny']=TRUE;
				if (!is_array($check_right)){
					if($val ['audit_type'] == 1)
						$right_array_temp['user_id']['self']['allow']=TRUE;
				}
				else
					if($val ['audit_type'] == 1)
						$current_right[]=$val ['control_list'];
			}
		}
		if (is_array($check_right)&&isset($current_right)){
			foreach ($check_right as $right_val){
				$this_right=FALSE;
				foreach ($current_right as $current_val){
					if (strpos($current_val,$right_val)!==FALSE)
						$this_right=TRUE;
				}
				if ($this_right===FALSE)
					$right_array_temp['user_id']['self']['allow']=FALSE;
			}
			if (!isset($right_array_temp['user_id']['self']['allow']))
				$right_array_temp['user_id']['self']['allow']=TRUE;
		}
		foreach ( $right_array_sort ['group'] as $val ) {
			if ($val['check_id']=='all'){
				if ($val ['audit_type'] == 1)
					$right_array_temp['group']['all']['allow']=TRUE;
				elseif ($val['audit_type'] == 0)
					$right_array_temp['group']['all']['deny']=TRUE;
			}
			else {
				if ($val ['audit_type'] == 1)
					$right_array_temp['group']['self']['allow']=TRUE;
				elseif ($val['audit_type'] == 0)
					$right_array_temp['group']['self']['deny']=TRUE;
			}
		}
		if (isset($right_array_temp['user_id']['all']['allow'])){//all user
			if ($right_array_temp['user_id']['all']['allow']==TRUE)
				$right_result=TRUE;
		}
		if (isset($right_array_temp['user_id']['all']['deny'])){//all user
			if ($right_array_temp['user_id']['all']['deny']==TRUE)
				$right_result=FALSE;
		}
		if (isset($right_array_temp['group']['all']['allow'])){//all group
			if ($right_array_temp['group']['all']['allow']==TRUE)
				$right_result=TRUE;
		}
		if (isset($right_array_temp['group']['all']['deny'])){//all group
			if ($right_array_temp['group']['all']['deny']==TRUE)
				$right_result=FALSE;
		}
		if (isset($right_array_temp['group']['self']['allow'])){//self group
			if ($right_array_temp['group']['self']['allow']==TRUE)
				$right_result=TRUE;
		}
		if (isset($right_array_temp['group']['self']['deny'])){//self group
			if ($right_array_temp['group']['self']['deny']==TRUE)
				$right_result=FALSE;
		}
			
		if (isset($right_array_temp['user_id']['self']['allow'])){//self user
			if ($right_array_temp['user_id']['self']['allow']==TRUE)
				$right_result=TRUE;
		}
		if (isset($right_array_temp['user_id']['self']['deny'])){//self user
			if ($right_array_temp['user_id']['self']['deny']==TRUE)
				$right_result=FALSE;
		}
//		print_r($right_array_temp);
		return $right_result;
	}
	function format_right($right_array) {
		While ( $it = $right_array->fetch_assoc () ) {
			if ($it ['id_type'] == 'group_id') {
				$right_array_sort ['group'] [] = $it;
			}
			if ($it ['id_type'] == 'right_id') {
				$right_array_sort ['right_id'] [] = $it;
			}
			if ($it ['id_type'] == 'user_id') {
				$right_array_sort ['user_id'] [] = $it;
			}
		}
		return $right_array_sort;
	}
}
//$asd=new discuss();
//$discuss_array=$asd->get_discuss(58);
//print_r($asd->discuss_back[67]);
//echo $discuss_array->num_rows;
class discuss{
	var $discuss_idea=array();
	var $discuss_back=array();
	var $discuss_count;
	function update_discuss($content="",$title="",$topic_id="",$father_id="",$send_by="",$update_type="insert",$topic_type="",$ip_analyse=FALSE,$read_time=0,$send_type=Null,$display_state=1){
		$log_access=new log();
		if ($send_by==""){
			if (isset($_SESSION['yaoyoa_com_uid']))
				$send_by=$_SESSION['yaoyoa_com_uid'];
			else
				$send_by=$log_access->get_ip();
		}
		if ($topic_type==""&&is_numeric($topic_id))$topic_type="discuss";
		if ($topic_id=="")$bbs_type="idea";
		if($ip_analyse){
			$access_id=$log_access->track(TRUE);
		}else
			$access_id=$log_access->track();
		$data_manage=new data_manage();
		$data_array=array("send_by"=>$send_by,"father_id"=>$father_id,"title"=>$title,"topic_type"=>$topic_type,"send_time"=>date("Y-m-d H:i:s"),"content"=>$content,"topic_id"=>$topic_id,"read_time"=>$read_time,"send_type"=>$send_type,"display_state"=>$display_state,"access_id"=>$access_id);
		$data_manage->update_array($data_array,"discuss",$update_type="insert");
	}
	function get_discuss($topic_id,$page_no=1,$page_size=15){
		if (!is_numeric($topic_id)||$topic_id<1)return FALSE;
		if (!is_numeric($page_no)||$page_no<1)$page_no=1;
		$sql_str="select * from discuss where topic_type='discuss' and topic_id='$topic_id' and isnull(father_id) and display_state='1' order by send_time desc";
		$conn = @db_connect ();
		$this->discuss_count=get_record_count($sql_str);
		$sql_str .= " limit " . ($page_no - 1) * $page_size . "," . $page_size;
		$discuss_array = $conn->query ( $sql_str );
		if (! $discuss_array || $discuss_array->num_rows == 0)
			return "err_000";
		else{
			While ( $discuss_idea_row = $discuss_array->fetch_assoc () ) {
				$this->discuss_idea[]=$discuss_idea_row;
			}
			$sql_str_back="select * from discuss where father_id<>'' and topic_id='$topic_id' order by send_time desc";
			$discuss_back_array = $conn->query ( $sql_str_back );
			While ( $discuss_back_row = $discuss_back_array->fetch_assoc () ) {
				$this->discuss_back[$discuss_back_row['father_id']][]=$discuss_back_row;
			}
		}
	}
}
//$article=new article;
//echo $article->update_content('6',"d",8940,"insert","yaoaa",33,1,"i");
//print_r($article->get_content("history","0416","title",FALSE,1,"all"));
//echo $article->get_catalog_name(7);
//echo $article->get_catalog_name(8);
class article {
	var $article_catalog_array=array();
	function get_catalog_name($catalog_id,$catalog_type="main_menu",$father_id=""){
		if ($catalog_id=="")return FALSE;
		if (count($this->article_catalog_array)==0){
			$sql_str="select catalog_name,id from catalog where catalog_type='$catalog_type'";
			if ($father_id!="")$sql_str.=" and father_id='$father_id'";
			$conn = @db_connect ();
			$this->article_catalog_array=db_result_to_array($conn->query ( $sql_str ));
		}
		foreach ($this->article_catalog_array as $catalog_name) {
			if ($catalog_name['id']==$catalog_id)return $catalog_name['catalog_name'];
		}
		return FALSE;
	}
	function get_history($query_date = "") {
		if ($query_date == "")
			$query_date = date ( "Y-m-d" );
		else {
			$date_validate = new validate_type ( );
			if (! $date_validate->is_date ( $query_date ))
				return array ("error_no" => "00", "error_info" => "the date is not valid" );
		}
		$sql_str = "select id,happen_date,title from history where display_state=1 and right(happen_date,4)='" . substr ( str_replace ( "-", "", $query_date ), 4 ) . "'";
		$conn = @db_connect ();
		$result = $conn->query ( $sql_str );
		if (! $result || $result->num_rows == 0)
			return "err_000";
		else
			return db_result_to_array ( $result );
	}
	function get_title() {
	
	}
	function get_accessory($relate_id,$relate_table="article"){
		$conn = @db_connect ();
		$sql_str = "select data_value,update_time from relate_data where relate_id='$relate_id' and relate_table='$relate_table' and data_type='accessory'";
		$result=$conn->query ( $sql_str );
		if (! $result || $result->num_rows == 0)
			return false;
		else
			return db_result_to_array ( $result );
	}
	//[update_content]update or insert the record into the target table
	public static function update_article($data_array,$update_type){
		if (is_numeric ( $update_type )) {
			data_manage::update_array($data_array,'article','update');
		}
		elseif ($update_type == "insert") {
			$data_array['author']=$_SESSION['yaoyoa_com_uid'];
			$data_array['write_time']=date ( "Y-m-d H:i:s" );
			$data_array['read_time']=0;
			$data_array['display_state']=1;
			data_manage::update_array($data_array,'article');
		}
		
	}
	function update_content($title, $content, $update_type = "insert", $key_word = "", $author = "", $read_time = "", $display_state = "", $catalog_id = "", $table_name = "article") {
		if (is_numeric ( $update_type )) {
			if (isset($_SESSION['yaoyoa_com_uid'])&&$author!="")$author=$_SESSION['yaoyoa_com_uid'];
			$sql_str = "update $table_name set";
			$sql_str = $title != "" ? (substr ( $sql_str, - 3 ) == "set" ? $sql_str . " title='$title'" : $sql_str . "," . " title='$title'") : $sql_str;
			$sql_str = $content != "" ? (substr ( $sql_str, - 3 ) == "set" ? $sql_str . " content='$content'" : $sql_str . "," . " content='$content'") : $sql_str;
			$sql_str = $key_word != "" ? (substr ( $sql_str, - 3 ) == "set" ? $sql_str . " key_word='$key_word'" : $sql_str . "," . " key_word='$key_word'") : $sql_str;
			$sql_str = $author != "" ? (substr ( $sql_str, - 3 ) == "set" ? $sql_str . " author='$author'" : $sql_str . "," . " author='$author'") : $sql_str;
			$sql_str = $read_time != "" ? (substr ( $sql_str, - 3 ) == "set" ? $sql_str . " read_time=$read_time" : $sql_str . "," . " read_time=$read_time") : $sql_str;
			$sql_str = $display_state != "" ? (substr ( $sql_str, - 3 ) == "set" ? $sql_str . " display_state=$display_state" : $sql_str . "," . " display_state=$display_state") : $sql_str;
			$sql_str = $catalog_id != "" ? (substr ( $sql_str, - 3 ) == "set" ? $sql_str . " catalog_id='$catalog_id'" : $sql_str . "," . " catalog_id='$catalog_id'") : $sql_str;
			if (substr ( $sql_str, - 3 ) == "set")
				return "err_000";
			$sql_str .= " where id=$update_type";
		}
		if ($update_type == "insert") {
			if ($title == "" || $content == "")
				return "err_000";
			$author = $author != "" ? $author : "yaoyoa";
			$read_time = $read_time != "" ? $read_time : 0;
			$display_state = $display_state != "" ? $display_state : 1;
			$catalog_id = $catalog_id != "" ? $catalog_id : "5";
			$write_time=date ( "Y-m-d H:i:s" );
			$sql_str = "insert into $table_name (title,content,key_word,author,read_time,display_state,catalog_id,write_time) values ('$title','$content','$key_word','$author',$read_time,$display_state,'$catalog_id','$write_time')";
		}
		if ($sql_str != "") {
			$conn = @db_connect ();
			$conn->query ( $sql_str );
			if ($update_type=="insert")return mysqli_insert_id($conn);
		}
	}
	function read_article($article_id = false, $table_name = "article") {
		if (! is_numeric ( $article_id ))
			return FALSE;
		$conn = @db_connect ();
		$sql_str = "update $table_name set read_time=read_time+1 where id=$article_id";
		$conn->query ( $sql_str );
	}
	//**[get_content]get the record id and record title
	//print_r(get_content("article","","prev",2));//return record id and title as a array
	function get_content($table_name = "article", $condition_val = "", $content_type = "title", $content_id = FALSE, $page_no = 1, $record_count = 10) {
		if (! is_numeric ( $record_count ) && ! $record_count == "all")
			$record_count = 10;
		if ($table_name=="")$table_name = "article";
		if ($content_type == "title") {
			if ($table_name == "article") {
				$sql_str = "select id,title,topic_pic_dir from article where display_state = 1";
				if ($condition_val != "")
					$sql_str .= " and catalog_id=$condition_val";
				$sql_str .= " order by write_time desc,id desc";
			}
			if ($table_name == "history") {
				$sql_str = "select id,happen_date,title from history where display_state = 1";
				if ($condition_val != "") {
					if (strlen ( $condition_val ) == 4)
						$sql_str .= " and right(happen_date,4)='" . $condition_val . "'";
					if (strlen ( $condition_val ) == 8)
						$sql_str .= " and happen_date='" . $condition_val . "'";
				}
				$sql_str .= " order by happen_date desc,id desc";
			}
		} elseif ($content_type == "prev") {
			if ($table_name == "article") {
				$sql_str = "select id,title,left(content,400) as content,length(content) as content_len,catalog_id,write_time from article where display_state = 1";
				if ($condition_val != "")
					if (is_array($condition_val)){
						$sql_str_temp="";
						foreach ($condition_val as $val1)
							$sql_str_temp.=" or catalog_id='$val1'";
						$sql_str.=" and (".substr($sql_str_temp,3).")";
					}
					else 
						$sql_str .= " and catalog_id=$condition_val";
				$sql_str .= " order by write_time desc,id desc";
			} elseif ($table_name == "history") {
				if ($condition_val != "" && strlen ( $condition_val ) >= 4)
					$condition_val = substr ( $condition_val, - 4 );
				else
					$condition_val = date ( "md" );
				$sql_str = "select id,title,left(content,400) as content,length(content) as content_len,happen_date as write_time from history where right(happen_date,4) = '$condition_val'";
			}
		} elseif ($content_type == "content" && $content_id != FALSE&&is_numeric($content_id)) {
			if ($table_name == "article") {
				$sql_str = "select id,title,key_word,content,catalog_id,write_time,author,read_time,display_state from article where id= '$content_id'";
			}
			if ($table_name == "history") {
				$sql_str = "select id,title,content,happen_date as write_time,send_by as author from history where display_state = '1' and id= '$content_id'";
			}
		} else
			return FALSE;
		if (($content_type == "title" || $content_type == "prev") && $record_count != "all") {
			$sql_str .= " limit " . ($page_no - 1) * $record_count . "," . $record_count;
		}
		$conn = @db_connect ();
		//die($sql_str);
		$result = $conn->query ( $sql_str );
		//echo $result->num_rows; //获取记录数
		if (! $result || $result->num_rows == 0){
			$error_handle=new error_handle();
			$error_handle->call_error("atc_001",$target_url);
			//return false; 
		}
		else
			return db_result_to_array ( $result );
	}
}
class log{
	//**[get_ip]get the client ip address
	//echo get_ip();//result127.0.0.1
	function get_ip() {
		if (getenv ( "HTTP_CLIENT_IP" ) && strcasecmp ( getenv ( "HTTP_CLIENT_IP" ), "unknown" ))
			$ip = getenv ( "HTTP_CLIENT_IP" );
		else if (getenv ( "HTTP_X_FORWARDED_FOR" ) && strcasecmp ( getenv ( "HTTP_X_FORWARDED_FOR" ), "unknown" ))
			$ip = getenv ( "HTTP_X_FORWARDED_FOR" );
		else if (getenv ( "REMOTE_ADDR" ) && strcasecmp ( getenv ( "REMOTE_ADDR" ), "unknown" ))
			$ip = getenv ( "REMOTE_ADDR" );
		else if (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], "unknown" ))
			$ip = $_SERVER ['REMOTE_ADDR'];
		else
			$ip = "unknown";
		return ($ip);
	}
	//**[ip_analyse]translate the ip address into geographic location
	//echo ip_analyse('202.103.24.68');//result本机地址
	function ip_analyse($ip_address) {
		//	list($ip1, $ip2, $ip3,$ip4) = split ('[/.-]', $ip_address);
		//	$longip=$ip1*16777216+$ip2*65536+$ip3*256+$ip4;
		$longip = $ip_address;
		$db = @db_connect ();
		$query = "select * from ip_address Where ip1<='$longip' AND ip2>='$longip' order by ip1 desc limit 0,1";
		$result = $db->query ( $query );
		if (! $result)
			return FALSE;
		else {
			$row = $result->fetch_assoc ();
			return ($row ['address']);
		}
		$result->free ();
		$db->close ();
	}
	function track($analyse_address=FALSE){
		$ip_address=$this->get_ip();
		$address_info=$analyse_address?$this->ip_analyse($ip_address):"";
		$page_dir=$redirect_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$refer_page=isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:"";
		$db = @db_connect ();
		$query = "insert into access_log (language,ip_address,browser,visit_time,address_info,page_dir,refer_page) values 
		('".$_SERVER['HTTP_ACCEPT_LANGUAGE']."','".$ip_address."','".$_SERVER['HTTP_USER_AGENT']."','".date("Y-m-d H:i:s")."','$address_info','$page_dir','".$refer_page."')";
		$result = $db->query ( $query );
		return mysqli_insert_id($db);
	}
}

//**[get_record_count]get record count of the target table
//echo get_record_count();//result76
function get_record_count($sql_str = "",$extra_condition = "5", $table_name = "article") {
	if ($table_name != "" || $sql_str != "") {
		$conn = @db_connect ();
		if ($sql_str == "" || strpos ( $sql_str, "select" ) === false) {
			if ($table_name == "article" && $extra_condition == "")
				$extra_condition = "catalog_id='5'";
			$sql_str = "select count(*) from $table_name where display_state=1 ";
			if ($table_name=="article"){
				if (is_array($extra_condition)){
					$sql_str_temp="";
					foreach ($extra_condition as $val1)
						$sql_str_temp.=" or catalog_id='$val1'";
					$sql_str.=" and (".substr($sql_str_temp,3).")";
				}
				elseif ($extra_condition!="") 
					$sql_str .= " and catalog_id='$extra_condition'";
			}
			$result = $conn->query ( $sql_str );
			if (! $result)
				return FALSE;
			else {
				$row = $result->fetch_array ();
				return $row [0];
			}
		} else {
			$sql_str = rawurldecode ( $sql_str );
			$result = $conn->query ( $sql_str );
			if (! $result)
				return FALSE;
			else {
				return $result->num_rows;
			}
		}
	}
}
function tag_link($tag=""){
	$link_str="";
	global $archive_page;
	if (!is_array($tag)){
		if (strpos($tag," ")!==FALSE)
			$tag= split('[/.-/ ]',$tag);
	}
	if (count($tag)>=1)
		foreach ($tag as $tag_val)
			if ($tag_val!="")$link_str.="<a href='$archive_page?tag=$tag_val'>$tag_val</a> ";
	return $link_str;
}
//**[content_stat]get the amount the content by day
//print_r(content_stat());
function content_stat($query_span = "week", $query_date = "", $extra_condition = array(5,6,7)) {
	if ($query_date == "")
		$query_date_end = date ( 'Y-m-d');
	if ($query_span == "week")
		$query_date_start = date ( 'Y-m-d', strtotime ( '-7 day' ) );
	elseif ($query_span == "month")
		$query_date_start = date ( 'Y-m-d', strtotime ( '-1 month' ) );
	$sql_str = "select date(write_time) as write_date,count(*) as article_count from article where display_state = 1 and date(write_time) between '$query_date_start' and '$query_date_end'";
	if ($extra_condition != "")
		if (is_array($extra_condition)){
			$sql_str_temp="";
			foreach ($extra_condition as $val1)
				$sql_str_temp.=" or catalog_id=$val1";
			$sql_str.=" and (".substr($sql_str_temp,3).")";
		}
		else 
			$sql_str .= " and catalog_id=$extra_condition";
//	if ($extra_condition != "")
//		$sql_str .= " and " . $extra_condition;
	$sql_str .= " group by date(write_time)";
	$conn = @db_connect ();
	$result = $conn->query ( $sql_str );
	if (! $result || $result->num_rows == 0)
		return "err_000";
	else
		return db_result_to_array ( $result );
}
//**[search_stat]find out the value of article count for the specify date if exist in the stat array
//search_stat();
function search_stat($stat_array = false, $query_date = "") {
	if (!$stat_array)
		$stat_array = content_stat ();
	if ($query_date == "")
		$query_date = date ( "Y-m-d" );
	if ($stat_array == "err_000" || count ( $stat_array ) < 1)
		return 0;
	for($j = 0; $j < count ( $stat_array ); $j ++) {
		if ($query_date == $stat_array [$j] ['write_date']){
			return $stat_array [$j] ['article_count'];}
	}
	return 0;
}
//**[page_link]return the href str
//echo page_link(3,2);
function page_link($record_count,$page_size=15, $page_no=1, $url_parameter = "",$ajax_action="") {
	if ($record_count <= 0)
		return "没有任何数据";
	$page_dir =$_SERVER ["PHP_SELF"];
	$page_count=ceil($record_count/$page_size);
	$link_str = $record_count."条记录 ";
	$link_str .= "共" . $page_count . "页 第" . $page_no . "页 ";
	$link_count = 5; //奇数有效 偶数+=1
	$middle_link = ceil ( $link_count / 2 );
	$page_start = $page_no + $middle_link - $link_count;
	$page_end = $page_no - $middle_link + $link_count;
	if ($page_start < 1) {
		$page_end += (1 - $page_start);
		$page_start = 1;
	}
	if ($page_end > $page_count) {
		$page_start -= ($page_end - $page_count);
		$page_end = $page_count;
	}
	if ($page_start < 1)
		$page_start = 1;
	if ($page_no != 1)
//		if ($ajax_action=="")
//			$link_str .="<a href=\"$page_dir?$url_parameter\">首页</a> ";
//		else 
//			$link_str .="<a href=\"javascript:$ajax_action(1".$url_parameter==""?"":",$url_parameter".");\">首页</a>";
		$link_str .= $ajax_action==""?"<a href=\"$page_dir?$url_parameter\">首页</a> ":"<a href=\"javascript:$ajax_action(1".($url_parameter==""?"":",'$url_parameter'").");\">首页</a> ";
	else
		$link_str .= "";
	if ($page_no - 1 > 0)
//		if ($ajax_action=="")
//			$link_str .="<a href=\"$page_dir?page_no=" . ($page_no - 1) . "&$url_parameter\">上页</a> ";
//		else 
//			$link_str .="<a href=\"javascript:$ajax_action(".($page_no - 1).$url_parameter==""?"":",$url_parameter".");\">上页</a> ";
		$link_str .= $ajax_action==""?"<a href=\"$page_dir?page_no=" . ($page_no - 1) . "&$url_parameter\">上页</a> ":"<a href=\"javascript:$ajax_action(".($page_no - 1).($url_parameter==""?"":",'$url_parameter'").");\">上页</a> ";
	else
		$link_str .= "";
	
	for($pj = $page_start; $pj <= $page_end; $pj ++) {
		if ($pj != $page_no) {
			$link_str .= $ajax_action==""?"<a href=\"$page_dir?page_no=$pj&$url_parameter\">$pj</a> ":"<a href=\"javascript:$ajax_action(".$pj.($url_parameter==""?"":",'$url_parameter'").");\">$pj</a> ";
		} else {
			$link_str .= $pj . " ";
		}
	}
	if ($page_no + 1 <= $page_count)
		$link_str .= $ajax_action==""?"<a href=\"$page_dir?page_no=" . ($page_no + 1) . "&$url_parameter\">下页</a> ":"<a href=\"javascript:$ajax_action(".($page_no + 1).($url_parameter==""?"":",'$url_parameter'").");\">下页</a> ";
	else
		$link_str .= "";
	if ($page_no != $page_count)
		$link_str .= $ajax_action==""?"<a href=\"$page_dir?page_no=$page_count&$url_parameter\">末页</a> ":"<a href=\"javascript:$ajax_action($page_count".($url_parameter==""?"":",'$url_parameter'").");\">末页</a>";
	else
		$link_str .= "";
	return $link_str;
}
//**[cut_string]return the string of defined length
//echo cut_string('你好你3好好',10,true);//result你好你3好...
function cut_string($input_string, $max_length, $extend_id) {
	$input_string = strip_tags ( $input_string );
	$recent_len = 0;
	for($k = 0; $k <= mb_strlen ( $input_string, 'UTF-8' ); $k ++) {
		$recent_len += mb_strwidth ( mb_substr ( $input_string, $k, 1, 'UTF-8' ), 'UTF-8' );
		if ($recent_len > $max_length || $k >= mb_strlen ( $input_string, 'UTF-8' )) {
			if ($extend_id && $k < mb_strlen ( $input_string, 'UTF-8' ))
				return mb_substr ( $input_string, 0, $k, 'UTF-8' ) . '...';
			else
				return mb_substr ( $input_string, 0, $k, 'UTF-8' );
			break;
		}
	}
}
//**[time_to_txt]translate the stand time format into chinese oral speaking
//echo time_to_txt("2009/3/09 02:38:21 PM");//result34秒前
function time_to_txt($input_time) {
	$int_time = time_to_int ( $input_time );
	$input_time_array = getdate ( $int_time );
	$now_time_array = getdate ( time () );
	// 	echo ($input_time_array["year"]==$now_time_array["year"]);
	if ($input_time_array ["year"] == $now_time_array ["year"] && $input_time_array ["month"] == $now_time_array ["month"]) {
		if ($input_time_array ["mday"] == ($now_time_array ["mday"] - 1))
			$time_txt = "昨天" . $input_time_array ["hours"] . "时" . $input_time_array ["minutes"] . "分";
		elseif ($input_time_array ["mday"] == $now_time_array ["mday"] - 2)
			$time_txt = "前天" . $input_time_array ["hours"] . "时" . $input_time_array ["minutes"] . "分";
		elseif ($input_time_array ["mday"] == $now_time_array ["mday"]) {
			if ($input_time_array ["hours"] != $now_time_array ["hours"])
				$time_txt = $now_time_array ["hours"] - $input_time_array ["hours"] . "小时前(" . $now_time_array ["hours"] . "点" . $now_time_array ["minutes"] . "分)";
			else {
				if ($input_time_array ["minutes"] != $now_time_array ["minutes"])
					$time_txt = $now_time_array ["minutes"] - $input_time_array ["minutes"] . "分钟前";
				else {
					if ($input_time_array ["seconds"] != $now_time_array ["seconds"])
						$time_txt = $now_time_array ["seconds"] - $input_time_array ["seconds"] . "秒前";
					else
						$time_txt = "刚刚";
				}
			}
		} else
			$time_txt = $input_time;
	} else
		$time_txt = $input_time;
	return $time_txt;
}
//**[time_to_int]translate stand time format into int
//echo time_to_int("2008/11/06 09:28:21 PM");//result1225978101
function time_to_int($stand_time) {
	//$date_time_string = "2008/11/06 09:28:21 PM"; 
	// 将字符串分解成3部分－日期、时间和上午/下午 
	$dt_elements = explode ( " ", $stand_time );
	// 分解日期 
	$date_elements = explode ( "/", $dt_elements [0] );
	// 分解时间 
	$time_elements = explode ( ":", $dt_elements [1] );
	// 如果是下午，我们将时间增加12小时以便得到24小时制的时间 
	if ($dt_elements [2] == "PM") {
		$time_elements [0] += 12;
	}
	// 输出结果 
	return mktime ( $time_elements [0], $time_elements [1], $time_elements [2], $date_elements [1], $date_elements [2], $date_elements [0] );
}
//$check_type_date="/^[0-9]{4}(\-|\/)[0-9]{1,2}(\\1)[0-9]{1,2}(|\s+[0-9]{1,2}(:[0-9]{1,2}){0,2})$/";
//echo preg_match($check_type_date,"2008/02-01");
//$ss=new validate_type;
//echo $ss->is_date("17040229",2);
class validate_type {
	function content($validate_str="",$content_type="text"){
		if ($content_type=="title"){
			
		}
	}
	public function check_str($str="",$check_type="text"){
		if ($str=="")return FALSE;
		$str_len=mb_strwidth($str, 'UTF-8');
		if ($check_type=="title"||$check_type=="key_word"){
			if ($str_len>200)return FALSE;
		}
		elseif ($check_type=="uid"||$check_type=="author"){
			if ($str_len>20)return FALSE;
		}
		
		for ($i=0;$i<strlen($str);$i++){
			
		}
	}
	function is_date($date_str, $date_type = 1) {
		if ($date_str != "" && (strlen ( $date_str ) == 10 || strlen ( $date_str ) == 8)) {
			$date_str = str_replace ( " ", "/", $date_str );
			$date_str = str_replace ( "\\", "/", $date_str );
			if ($date_type == 1) { //2008-02-01||2008/02/01
				if (strlen ( $date_str ) != 10)
					return FALSE;
				if (! is_numeric ( substr ( $date_str, 0, 4 ) ))
					return FALSE;
				if (! is_numeric ( substr ( $date_str, 5, 2 ) ))
					return FALSE;
				if (! is_numeric ( substr ( $date_str, 8, 2 ) ))
					return FALSE;
				if ((substr ( $date_str, 4, 1 ) != "-" || substr ( $date_str, 7, 1 ) != "-") && (substr ( $date_str, 4, 1 ) != "/" || substr ( $date_str, 7, 1 ) != "/"))
					return FALSE;
				$year_str = substr ( $date_str, 0, 4 );
				$month_str = substr ( $date_str, 5, 2 );
				$day_str = substr ( $date_str, 8, 2 );
				if ($month_str > 12 || $month_str < 1)
					return FALSE;
				if ($day_str > 31 || $day_str < 1)
					return FALSE;
			} elseif ($date_type == 2) { //20080201
				if (strlen ( $date_str ) != 8 && ! is_numeric ( $date_str ))
					return FALSE;
				$year_str = substr ( $date_str, 0, 4 );
				$month_str = substr ( $date_str, 4, 2 );
				$day_str = substr ( $date_str, 6, 2 );
			}
			if (isset ( $month_str ) && isset ( $day_str )) {
				if (! checkdate ( $month_str, $day_str, $year_str ))
					return FALSE;
			}
		} else
			return FALSE;
		return TRUE;
	}
	function is_leap_year($year_str = '') {
		if ($year_str == "")
			$year_str = date ( "Y" );
		if (($year_str % 400 == 0 || ($year_str % 4 == 0 && $year_str % 100 != 0))) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
}
//$ss=new date_time;
//echo $ss->format_date();
//set_time_limit(0);
//chg_history_date();
function chg_history_date() {
	$conn = @db_connect ();
	$result = $conn->query ( "select * from history where id>1442" );
	$result = db_result_to_array ( $result );
	foreach ( $result as $row ) {
		//		echo strlen(trim($row['happen_date']))."<br>";
		if (strlen ( trim ( $row ['happen_date'] ) ) == 7) {
			$conn->query ( "update history set happen_date=concat(left(happen_date,3),'-',right(left(happen_date,5),2),'-',right(left(happen_date,7),2)) where id=" . $row ['id'] );
		} elseif (strlen ( trim ( $row ['happen_date'] ) ) == 8) {
			$conn->query ( "update history set happen_date=concat(left(happen_date,4),'-',right(left(happen_date,6),2),'-',right(left(happen_date,8),2)) where id=" . $row ['id'] );
		}
	}

}
class date_time {
	function now() {
		return date ( "Y-m-d H:i:s" );
	}
	function date() {
		return date ( "Y-m-d" );
	}
	function time() {
		return date ( "H:i:s" );
	}
	function format_date($date_str) {
		if (strlen ( $date_str ) == 8 && is_numeric ( $date_str ))
			return $date_str;
		if (! strpos ( $date_str, "/" )) {
			$date_element = explode ( $date_str, '/' );
			print_r ( $date_element );
		}
	
	}
	//**[time_to_txt]translate the stand time format into chinese oral speaking
	//echo time_to_txt("2009/3/09 02:38:21 PM");//result34秒前
	function time_to_txt($input_time) {
		$int_time = time_to_int ( $input_time );
		$input_time_array = getdate ( $int_time );
		$now_time_array = getdate ( time () );
		// 	echo ($input_time_array["year"]==$now_time_array["year"]);
		if ($input_time_array ["year"] == $now_time_array ["year"] && $input_time_array ["month"] == $now_time_array ["month"]) {
			if ($input_time_array ["mday"] == ($now_time_array ["mday"] - 1))
				$time_txt = "昨天" . $input_time_array ["hours"] . "时" . $input_time_array ["minutes"] . "分";
			elseif ($input_time_array ["mday"] == $now_time_array ["mday"] - 2)
				$time_txt = "前天" . $input_time_array ["hours"] . "时" . $input_time_array ["minutes"] . "分";
			elseif ($input_time_array ["mday"] == $now_time_array ["mday"]) {
				if ($input_time_array ["hours"] != $now_time_array ["hours"])
					$time_txt = $now_time_array ["hours"] - $input_time_array ["hours"] . "小时前(" . $now_time_array ["hours"] . "点" . $now_time_array ["minutes"] . "分)";
				else {
					if ($input_time_array ["minutes"] != $now_time_array ["minutes"])
						$time_txt = $now_time_array ["minutes"] - $input_time_array ["minutes"] . "分钟前";
					else {
						if ($input_time_array ["seconds"] != $now_time_array ["seconds"])
							$time_txt = $now_time_array ["seconds"] - $input_time_array ["seconds"] . "秒前";
						else
							$time_txt = "刚刚";
					}
				}
			} else
				$time_txt = $input_time;
		} else
			$time_txt = $input_time;
		return $time_txt;
	}
}
class data_manage{
	public static function update_array($data_array=FALSE,$table_name,$update_type="insert"){
		if ($data_array!==FALSE){
			$data_dim=get_max_dim($data_array);
			if ($data_dim==1){
				if ($update_type=="insert")
					$sql_relate_data="insert into $table_name set ";
				elseif ($update_type=="update")
					$sql_relate_data="update $table_name set ";
				foreach ($data_array as $key1=>$val1){
					if ($key1!="id"&&$val1!=""&&$val1!=NULL)
						$sql_relate_data.=$key1."='".$val1."',";
					else
						$update_id=$val1;
				}
				$sql_relate_data=substr($sql_relate_data,0,strlen($sql_relate_data)-1);
				if ($update_type=="update")
					$sql_relate_data.=" where id=".$update_id;
				if ($sql_relate_data){
					$conn = @db_connect ();
					if (!@$conn->query ($sql_relate_data))
						return "db_0001";
					else
						if ($update_type=='insert')return mysqli_insert_id($conn);
				}
			}
			elseif ($data_dim==2){
				foreach ($data_array as $val2){
					$update_id=NULL;
					if ($update_type=="insert")
						$sql_relate_data="insert into $table_name set ";
					elseif ($update_type=="update")
						$sql_relate_data="update $table_name set ";
					foreach ($val2 as $key3=>$val3){
						if ($key3!="id")
							$sql_relate_data.=$key3."='".$val3."',";
						else
							$update_id=$val3;
					}
					$sql_relate_data=substr($sql_relate_data,0,strlen($sql_relate_data)-1);
					if ($update_type=="update"&&isset($update_id))
						$sql_relate_data.=" where id=".$update_id;
					elseif ($update_type=="update"&&!isset($update_id))
						$sql_relate_data=FALSE;
					if ($sql_relate_data){
						$conn = @db_connect ();
						if (!@$conn->query ($sql_relate_data))
							return "db_0001";
						else
							if ($update_type=='insert')return mysqli_insert_id($conn);
					}
				}
			}
		}
		else
			return FALSE;
	}
	//**[delete_record]
	////delete_record('weather',2);//delete the record
	function delete_record($table_name, $record_id) {
		if ($table_name != '' && is_numeric( $record_id )) {
			$conn = @db_connect ();
			$sql_str = "delete from $table_name where id=$record_id";
			$conn->query ( $sql_str );
		}
	}
}
//$dd=new data_manage();
//$dd->update_array(array(0=>array("id"=>3,"data_value"=>"dddffdd","data_type"=>"accessory","relate_id"=>35)),'relate_data',"insert");
//$dd->update_data(array("dd"=>333));
class upload{
	var $save_name;
	var $save_path;
	var $file_format = NULL;//array('gif','jpg','mp3','mov','doc','sql','application/octet-stream');
	var $over_write = 0;
	var $max_size = 10000000;
	var $ext;
	var $error_no;
	var $return_array= array();
	var $return_info= array();
	var $upload_relate_info;
	function upload($save_path, $file_format='',$max_size = 0, $over_write = 0) {
		$this->set_save_path($save_path);
		$this->set_file_format($file_format);
		$this->set_max_size($max_size);
		$this->set_over_write($over_write);
		$this->error_no = 0;
	}
	function do_upload($element_id,$change_name=0,$target_url="",$upload_relate_info=Null){
		if (is_array($upload_relate_info))
			$this->upload_relate_info=$upload_relate_info;
		if(isset($_FILES[$element_id])){
			$file_array = $_FILES[$element_id];
			if(is_array($file_array['name'])){
				for($i = 0; $i < count($file_array['name']); $i++){
					$ar['tmp_name'] = $file_array['tmp_name'][$i];
					$ar['name'] = $file_array['name'][$i];
					$ar['type'] = $file_array['type'][$i];
					$ar['size'] = $file_array['size'][$i];
					$ar['error'] = $file_array['error'][$i];
					$this->get_ext($ar['name']);
					$this->set_save_name($change_name == 1 ? '' : $ar['name']);
					if($this->copy_file($ar)){
						$this->return_array[] =  $this->return_info;
					}else{
						$this->return_info['error'] = $this->errmsg();
						$this->return_array[] =  $this->return_info;
					}
				}
				//return $this->error_no ?  false :  true;
			}else{
				$this->get_ext($file_array['name']);
				$this->set_save_name($change_name == 1 ? '' : $file_array['name']);
				if($this->copy_file($file_array)){
					$this->return_array[] =  $this->return_info;
				}else{
					$this->return_info['error'] = $this->errmsg();
					$this->return_array[] =  $this->return_info;
				}
				//return $this->error_no ?  false :  true;
			}
			if ($this->error_no!=""&&$this->error_no!="ul_4"){
				$error_handle=new error_handle();
				$error_handle->call_error($this->error_no,$target_url);				
			}
		}
	}
	function copy_file($file_array){
		$this->return_info = array();
		$this->return_info['name'] = $file_array['name'];
		$this->return_info['save_name'] = $this->save_name;
		$this->return_info['size'] = number_format( ($file_array['size'])/1024 , 0, '.', ' ');
		$this->return_info['type'] = $file_array['type'];
		if (!$this->validate_format()){
			$this->error_no = 'ul_11';
			return false;
		}
		if(!@is_writable($this->save_path)){
			$this->error_no = 'ul_12';
			return false;
		}
		if ($this->max_size != 0 ){
			if ($file_array["size"] > $this->max_size){
				$this->error_no = 'ul_14';
				return false;
			}
		}
		if(!@move_uploaded_file($file_array["tmp_name"], $this->save_path.$this->save_name)){
			$this->error_no = "ul_".$file_array["error"];
			return false;
		}
		else{
			$add_record=new data_manage();
			$add_record->update_array(array("data_value"=>$this->save_name,"data_type"=>"accessory","relate_id"=>$this->upload_relate_info['id'],'relate_table'=>$this->upload_relate_info['relate_table'],'update_time'=>date('Y-m-d H:i:s')),'relate_data',"insert");
			return true;
		}
	}	
	function set_save_name($save_name=""){
		if ($save_name == ''||strlen($save_name)>100){
			$name = date('YmdHis')."_".rand(100,999).'.'.$this->ext;
		}
		else{
			$name = $save_name;
		}
		if(file_exists($this->save_path . $name)){
			$name = date('YmdHis')."_".rand(100,999).'.'.$this->ext;
		}
		$this->save_name = $name;
	}
	function validate_format(){
		if(!is_array($this->file_format)
			|| in_array(strtolower($this->ext), $this->file_format) 
			|| in_array(strtolower($this->return_info['type']), $this->file_format)
			|| $this->ext=="" ){
			return true;
		}
		else
			return false;
	}
	function get_ext($file_name){
		$ext = explode(".", $file_name);
		$ext = $ext[count($ext) - 1];
		$this->ext = strtolower($ext);
	}
	function set_max_size($max_size){
		$this->max_size = $max_size;
	}
	function set_file_format($file_format){
		if(is_array($file_format)){$this->file_format = $file_format ;}
	}

	function set_over_write($over_write){
		$this->over_write = $over_write;
	}
	function get_info(){
		return $this->return_array;
	}
	function set_save_path($save_path){
		$this->save_path = substr( str_replace("\\","/", $save_path) , -1) == "/" 
		? $save_path : $save_path."/";
	}
	function errmsg(){
		$uploadClassError = array(
			'ul_0'	=>'There is no error, the file uploaded with success. ',
			'ul_1'	=>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
			'ul_2'	=>'The uploaded file exceeds the MAX_FILE_SIZE that was specified in the HTML form.',
			'ul_3'	=>'The uploaded file was only partially uploaded. ',
			'ul_4'	=>'No file was uploaded. ',
			'ul_6'	=>'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. ',
			'ul_7'	=>'Failed to write file to disk. Introduced in PHP 5.1.0. ',
			'ul_10'	=>'Input name is not unavailable!',
			'ul_11'	=>'The uploaded file is Unallowable!',
			'ul_12'	=>'Directory unwritable!',
			'ul_13'	=>'File exist already!',
			'ul_14'	=>'File is too big!',
			'ul_15'	=>'Delete file unsuccessfully!'
			);
		if ($this->error_no == 0)
			return false;
		else
			return $uploadClassError[$this->error_no];
	}
}
//**{phone_location}get the phone area
//$ss=new phone_location();
//print_r($ss->get_phone_address("13886084"));//return the area data as a array
class phone_location { //query the area of mobile phone
	function WaitForLine($f, $keyword) { //等待出现含有关键字的行，返回该行
		while ( ! feof ( $f ) ) {
			$l = fgets ( $f );
			if (strstr ( $l, $keyword ) !== FALSE)
				return $l;
		}
		return NULL;
	}
	function get_phone_address($q) {
		if ($q == "")
			return FALSE;
		if (strlen ( $q ) >= 7) {
			$bb = "000000";
			$q .= substr ( $bb, 0, 11 - strlen ( $q ) );
		} else {
			return FALSE;
		}
		if (preg_match ( '/^134[0-8]\d{7}|(13[5-9]|15[01789]|188)\d{8}$/', $q )) { //移动手机号码
			$f = fsockopen ( 'www.chinamobile.com', 80, $errno, $errstr, 5 );
			stream_set_timeout ( $f, 3 );
			fwrite ( $f, "POST /service/online/location.do HTTP/1.1\r\n" . "Host: www.chinamobile.com\r\n" . "Referer: http://www.chinamobile.com/service/online/location.do\r\n" . "Content-Type: application/x-www-form-urlencoded\r\n" . "Content-Length: 32\r\n" . "\r\n" . "sectionNum=" . $q . "&urlType=1\r\n" );
			$this->WaitForLine ( $f, iconv ( 'utf-8', 'gbk', '所属省份：' ) );
			$l = fgets ( $f );
			$province = iconv ( 'gbk', 'utf-8', str_replace ( array ('<TD >', '</TD>' ), '', trim ( $l ) ) );
			$this->WaitForLine ( $f, iconv ( 'utf-8', 'gbk', '所属城市：' ) );
			$l = fgets ( $f );
			$city = iconv ( 'gbk', 'utf-8', str_replace ( array ('<TD >', '</TD>' ), '', trim ( $l ) ) );
			fclose ( $f );
			//	echo json_encode(array('type'=>'mobile','company'=>'cmcc','province'=>$province,'city'=>$city,'result'=>($province==$city)?$city:$province.' '.$city));
			return array ('type' => 'mobile', 'company' => '中国移动', 'province' => $province, 'city' => $city, 'result' => ($province == $city) ? $city : $province . ' ' . $city );
		} else if (preg_match ( '/^13[012]\d{8}$/', $q ) || preg_match ( '/^15[56]\d{8}$/', $q )) { //联通手机号码
			$f = fsockopen ( 'www.sh.chinaunicom.com', 80, $errno, $errstr, 5 );
			stream_set_timeout ( $f, 3 );
			fwrite ( $f, "POST /ehall/area/queryAreaByPhone.do HTTP/1.0\r\n" . "Host: www.sh.chinaunicom.com\r\n" . "Content-Type: application/x-www-form-urlencoded\r\n" . "Content-Length: 37\r\n" . "\r\n" . "phone=" . $q . "&submit=%CC%E1%BD%BB\r\n" );
			$this->WaitForLine ( $f, iconv ( 'utf-8', 'gbk', '您输入的手机号码归属于：' ) );
			fgets ( $f ); //跳过空行
			$l = fgets ( $f );
			$result = iconv ( 'gbk', 'utf-8', str_replace ( array ('<td width="40%"align="left" class="font_black">', '</td>' ), '', trim ( $l ) ) );
			fclose ( $f );
			//	echo json_encode(array('type'=>'mobile','company'=>'unicom','result'=>$result));
			return (array ('type' => 'mobile', 'company' => '中国联通', 'result' => $result ));
		} else if (preg_match ( '/^(1[35]3|189)\d{8}$/', $q )) { //电信手机号码
			$f = fsockopen ( 'www2.ct10000.com', 80, $errno, $errstr, 5 );
			stream_set_timeout ( $f, 3 );
			fwrite ( $f, "POST /cdma/index.jsp HTTP/1.1\r\n" . "Host: www2.ct10000.com\r\n" . "Content-Type: application/x-www-form-urlencoded\r\n" . "Content-Length: 19\r\n" . "\r\n" . "webcode=" . $q . "\r\n" );
			$l = $this->WaitForLine ( $f, iconv ( 'utf-8', 'gbk', '您号码的归属地为' ) );
			$matches = array ();
			preg_match ( '/target="_blank">(.+)<\/a>/', iconv ( 'gbk', 'utf-8', $l ), $matches );
			$result = $matches [1];
			fclose ( $f );
			//	echo json_encode(array('type'=>'mobile','company'=>'telecom','result'=>$result));
			return (array ('type' => 'mobile', 'company' => '中国电信', 'result' => $result ));
		} else if (preg_match ( '/^.+\..+$/', $q )) { //域名或IP地址
			if (preg_match ( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $q ))
				$ip = $q;
			else
				$ip = gethostbyname ( $q );
			$result = '';
			if (preg_match ( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $ip )) {
				$f = fsockopen ( 'www.ip.cn', 80, $errno, $errstr, 3 );
				stream_set_timeout ( $f, 3 );
				fwrite ( $f, "GET /getip.php?action=queryip&ip_url=" . $ip . " HTTP/1.1\r\n" . "Host: www.ip.cn\r\n" . "\r\n" );
				$l = $this->WaitForLine ( $f, '</span>' );
				$matches = array ();
				preg_match ( '/来自：(.*)$/', iconv ( 'gbk', 'utf-8', $l ), $matches );
				$result = trim ( $matches [1] );
				fclose ( $f );
			}
			//	echo json_encode(array('type'=>'ip','ip'=>$ip,'result'=>$result));
			return (array ('type' => 'ip', 'ip' => $ip, 'result' => $result ));
		} else
			return FALSE;
	}
}
function get_max_dim($v_dim)
{
    if(!is_array($v_dim)) return 0;
    else
    {
        $max1 = 0;
        foreach($v_dim as $item1)
        {
            $t1 = get_max_dim($item1);
            if( $t1 > $max1) $max1 = $t1;
        }
        return $max1 + 1;
    }
}

/* Author: heiyeluren */
/* 过滤所有GET过来变量 */
foreach ( $_GET as $get_key => $get_var ) {
	if (is_numeric ( $get_var ))
		if (is_numeric ( $get_var )) {
			$get [strtolower ( $get_key )] = get_int ( $get_var );
		} else {
			$get [strtolower ( $get_key )] = get_str ( $get_var );
		}
}

/* 过滤所有POST过来的变量 */
foreach ( $_POST as $post_key => $post_var ) {
	if (is_numeric ( $post_var )) {
		$post [strtolower ( $post_key )] = get_int ( $post_var );
	} else {
		$post [strtolower ( $post_key )] = get_str ( $post_var );
	}
}

/* 过滤函数 */
//整型过滤函数
function get_int($number) {
	return intval ( $number );
}
//字符串型过滤函数
function get_str($string) {
	if (! get_magic_quotes_gpc ()) {
		return addslashes ( $string );
	}
	return $string;
}
?>